#include "tserver.h"
#include "tdatabaseinfo.h"
#include <QDataStream>
#include "inicpp.hpp"
#include "tserialize.h"
TServer::TServer(QObject* parent)
    : QTcpServer(parent)
{
    inicpp::IniManager ini("D:/实习日志/internship-logss/TCP/TServer/x64/Debug/TServer.ini");
    QString port = QString::fromStdString(ini["Network"]["Port"]);
    listen(QHostAddress::Any, port.toUShort());
    connect(this, &QTcpServer::newConnection, this, &TServer::onNewClientConnect);
    qDebug() << "listening :" << port;
}

TServer::~TServer()
{}

void TServer::onNewClientConnect()
{
    qDebug() << __func__;
    QTcpSocket* clientConnection = nextPendingConnection();
    connect(clientConnection, &QTcpSocket::readyRead, this, &TServer::onClientReadyRead);
    connect(clientConnection, &QTcpSocket::disconnected, this, &TServer::onClientDisconnect);
}

void TServer::onClientReadyRead()
{

    auto socket = static_cast<QTcpSocket*>(sender());
    auto byteArray = socket->readAll();

    qDebug() << byteArray;

    while(byteArray.size())
    {
        qint64 len;
        QDataStream ds(byteArray);
        ds >> len;
        if(byteArray.size())
        takeAction(socket, byteArray.left(len).mid(8));
        byteArray = byteArray.mid(len);
    }
}

void TServer::onClientDisconnect()
{
    qDebug() << __func__;
    auto socket = static_cast<QTcpSocket*>(sender());
    QString key;
    for (auto it = m_socketData.begin(); it != m_socketData.end(); ++it)
    {
        if (it.value() == socket)
        {
            key = it.key();
            break;
        }
    }
    m_socketData.remove(key);
    socket->deleteLater();
}

void TServer::takeAction(QTcpSocket*socket,QByteArray byteArray)
{
    OPERATOR type = getOperatorType(byteArray);
        switch (type)
        {
        case OPERATOR::SEND_MESSAGE:           sendMessage(socket, byteArray); break;
        //case OPERATOR::GET_CONTACT:          getContact(socket, byteArray);  break;
        default:                        qDebug() << "识别失败";                 break;
        }
}

void TServer::sendMessage(QTcpSocket* sender, const QByteArray& byteArray)
{
    OPERATOR Type;
    QByteArray data;
    QDataStream ds(byteArray);
    ds >> Type >> data;
    qDebug() << static_cast<int>(Type);
    qDebug() << QString::fromUtf8(data);

    sender->write(TSerialize::serialize(OPERATOR::SEND_MESSAGE,data));//将数据写回
}

OPERATOR TServer::getOperatorType(QByteArray& byteArray)
{
    OPERATOR Type;
    QByteArray data;
    QDataStream ds(byteArray);
    ds >> Type;
    return Type;
}
